package com.example.user_center.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.user_center.common.BaseResponse;
import com.example.user_center.common.ErrorCode;
import com.example.user_center.common.ResultUtils;
import com.example.user_center.contant.UserContent;
import com.example.user_center.exception.BusinessException;
import com.example.user_center.mapper.UserMapper;
import com.example.user_center.pojo.User;
import com.example.user_center.pojo.request.UserLoginRequest;
import com.example.user_center.pojo.request.UserRegisterRequest;
import com.example.user_center.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.user_center.contant.UserContent.USER_LOGIN_STATE;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    // 注册接口
    @PostMapping("/register")
    public BaseResponse<Long> userRegister (@RequestBody UserRegisterRequest userRegisterRequest) {

        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求体为空...");
        }

        long id = userService.userRegister(userRegisterRequest);

        if (StringUtils.isBlank(userRegisterRequest.getUserAccount()) || StringUtils.isBlank(userRegisterRequest.getUserPassword())
                || StringUtils.isBlank(userRegisterRequest.getCheckPassword()) || StringUtils.isBlank(userRegisterRequest.getPlanetCode())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空...");
        }

        return ResultUtils.success(id);
    }

    // 登录接口
    @PostMapping("/login")
    public BaseResponse<User> userLogin (@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {

        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求体为空...");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        User user = userService.userLogin(userAccount, userPassword, request);
        // 前端session中存放了该登录用户的基本信息
        if (StringUtils.isBlank(userAccount) || StringUtils.isBlank(userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数为空...");
        }
        //
        return ResultUtils.success(user);
    }

    // 登录接口
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout (HttpServletRequest request) {

        if (request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求体为空...");
        }

        Integer i = userService.userLogout(request);
        return ResultUtils.success(i);
    }

    // 获取用户登录态信息
    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser (HttpServletRequest request) {

        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User)attribute;
        // 判断用户是否为空(也就是是否登录过)
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN,"用户未登录...");
        }
        // 获取本用户最新状态 并返回
        Long id = currentUser.getId();
        // todo 校验方法是否合法
        User user = userService.getById(id);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    // 查询接口
    @GetMapping("/search")
    public BaseResponse<List<User>> userSearch( String username, HttpServletRequest request) {

        // 判断是否是管理员
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_AUTH,"不是管理员没有权限...");
        }
        // 根据用户名查询用户 返回 用户列表
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            // mp里面的like方法 如果val没有传值 就是模糊查询
            userQueryWrapper.like("username",username);
        }

        List<User> users = userMapper.selectList(userQueryWrapper);
        // 用户脱敏
        List<User> userList = users.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());

        return ResultUtils.success(userList);
    }

    // 删除接口
    @PostMapping("/delete")
    public BaseResponse<Boolean> userDelete (@RequestParam long id, HttpServletRequest request) {

        // 判断是否是管理员
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_AUTH,"不是管理员没有权限...");
        }

        if (id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数错误...");
        }

        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    // 判断是否是管理员
    public boolean isAdmin (HttpServletRequest request) {

        User user = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null || user.getUserRole() != UserContent.ADMIN_ROLE) {
            log.info("用户权限不足...");
            return false;
        }
        return true;
    }
}
